from celery import Celery
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from datetime import datetime

from app.core.config import settings
from app.db.models import Click

celery = Celery('tasks', broker=settings.REDIS_URL)

# 同步数据库连接
engine = create_engine(settings.DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

@celery.task
def track_click(url_id: int, ip_address: str, user_agent: str):
    """异步记录点击事件"""
    db = SessionLocal()
    try:
        click = Click(
            url_id=url_id,
            ip_address=ip_address,
            user_agent=user_agent,
            clicked_at=datetime.utcnow()
        )
        db.add(click)
        db.commit()
    finally:
        db.close() 